package com.waterfairy.http;


import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by water_fairy on 2017/2/22.
 */

public class RetrofitHttpClient {

    private Retrofit retrofit;

    private RetrofitHttpClient(String baseUrl, boolean hasGson, Interceptor interceptor) {
        OkHttpClient.Builder okHttpClient = new OkHttpClient().newBuilder();


        try {
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[]{};
                }

                public void checkClientTrusted(X509Certificate[] chain, String authType) {

                }

                public void checkServerTrusted(X509Certificate[] chain, String authType) {

                }
            }};


            HostnameVerifier hostnameVerifier = (hostname, session) -> true;
            okHttpClient.hostnameVerifier(hostnameVerifier);
            SSLContext sslContext = null;
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            okHttpClient.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }


        if (interceptor != null)
            okHttpClient.addInterceptor(interceptor);
        OkHttpClient httpClient = okHttpClient.build();
        okHttpClient.connectTimeout(60, TimeUnit.SECONDS);
        okHttpClient.readTimeout(60, TimeUnit.SECONDS);
        okHttpClient.writeTimeout(60, TimeUnit.SECONDS);
        Retrofit.Builder client = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(httpClient);
        if (hasGson) {
            client.addConverterFactory(GsonConverterFactory.create());
        }
        retrofit = client.build();
    }

    public static RetrofitHttpClient build(String baseUrl, boolean hasGson, Interceptor interceptor) {
        return new RetrofitHttpClient(baseUrl, hasGson, interceptor);
    }


    public Retrofit getRetrofit() {
        return retrofit;
    }
}
